import { IPC_CHANNELS } from 'shared/ipcChannels'
import { createLogger } from '#/logger'
import { accountManager } from '#/managers/AccountManager'
import { errorMessage, typedIpcMainHandle } from '#/utils'

const TASK_NAME = '达人卷'

function setupIpcHandlers() {
  // 获取推广商品列表
  typedIpcMainHandle(
    IPC_CHANNELS.darenJuan.fetchPromotions,
    async (_, accountId: string) => {
      const logger = createLogger(
        `@${accountManager.getAccountName(accountId)}`,
      ).scope(TASK_NAME)

      try {
        const session = accountManager.getSession(accountId)
        if (!session) {
          throw new Error('未找到对应的会话，请先连接到直播控制台')
        }

        // 获取浏览器上下文
        const browserSession = (session as any).browserSession
        if (!browserSession) {
          throw new Error('浏览器会话不存在')
        }

        const page = browserSession.page
        logger.info('开始获取达人卷推广数据...')

        // 确保当前页面在控制台页面
        const currentUrl = page.url()
        if (!currentUrl.includes('buyin.jinritemai.com/dashboard/live/control')) {
          await page.goto('https://buyin.jinritemai.com/dashboard/live/control', {
            waitUntil: 'networkidle',
          })
          await page.waitForTimeout(2000)
        }

        // 监听网络请求，拦截 promotions_v2 接口的响应
        let promotionsData: any = null
        const responsePromise = new Promise((resolve, reject) => {
          const timeout = setTimeout(() => {
            reject(new Error('获取数据超时，请确保页面已加载完成'))
          }, 30000) // 30秒超时

          page.on('response', async (response: any) => {
            const url = response.url()
            if (url.includes('/api/anchor/livepc/promotions_v2')) {
              try {
                const data = await response.json()
                clearTimeout(timeout)
                resolve(data)
              } catch (err) {
                logger.warn('解析响应数据失败:', errorMessage(err))
              }
            }
          })
        })

        // 触发页面刷新或滚动，让页面自动发起请求
        logger.info('触发页面刷新以获取数据...')
        await page.reload({ waitUntil: 'networkidle' })
        
        // 等待接口响应
        promotionsData = await responsePromise

        logger.success('成功获取达人卷推广数据')
        
        return {
          success: true,
          data: promotionsData,
        }
      } catch (error) {
        logger.error('获取达人卷推广数据失败:', errorMessage(error))
        return {
          success: false,
          error: errorMessage(error),
        }
      }
    },
  )

  // 获取佣金率数据
  typedIpcMainHandle(
    IPC_CHANNELS.darenJuan.fetchCommissionRates,
    async (_, accountId: string) => {
      const logger = createLogger(
        `@${accountManager.getAccountName(accountId)}`,
      ).scope(TASK_NAME)

      try {
        const session = accountManager.getSession(accountId)
        if (!session) {
          throw new Error('未找到对应的会话，请先连接到直播控制台')
        }

        const browserSession = (session as any).browserSession
        if (!browserSession) {
          throw new Error('浏览器会话不存在')
        }

        const page = browserSession.page
        logger.info('开始获取佣金率数据...')

        // 导航到优惠券管理页面
        logger.info('导航到优惠券管理页面...')
        await page.goto('https://buyin.jinritemai.com/dashboard/marketing/coupon-manager', {
          waitUntil: 'networkidle',
        })
        await page.waitForTimeout(2000)

        // 点击"新建达人券"按钮
        logger.info('点击"新建达人券"按钮...')
        try {
          // 尝试多种选择器
          const createButton = await page.waitForSelector(
            'button:has-text("新建达人券"), button:has-text("新建")',
            { timeout: 10000 }
          )
          await createButton.click()
          logger.info('成功点击新建达人券按钮')
        } catch (err) {
          logger.error('点击新建达人券按钮失败，尝试备用方案')
          await page.evaluate(() => {
            const buttons = Array.from(document.querySelectorAll('button'))
            const btn = buttons.find(b => b.textContent?.includes('新建达人券') || b.textContent?.includes('新建'))
            if (btn) {
              (btn as HTMLButtonElement).click()
            }
          })
        }
        await page.waitForTimeout(2000)

        // 点击"选择商品"按钮
        logger.info('等待弹窗加载并点击"选择商品"按钮...')
        try {
          const selectProductButton = await page.waitForSelector(
            'button:has-text("选择商品")',
            { timeout: 10000 }
          )
          await selectProductButton.click()
          logger.info('成功点击选择商品按钮')
        } catch (err) {
          logger.error('点击选择商品按钮失败，尝试备用方案')
          await page.evaluate(() => {
            const buttons = Array.from(document.querySelectorAll('button'))
            const btn = buttons.find(b => b.textContent?.includes('选择商品'))
            if (btn) {
              (btn as HTMLButtonElement).click()
            }
          })
        }
        await page.waitForTimeout(2000)

        // 设置监听器，拦截接口响应
        logger.info('设置接口监听器...')
        const allPromotions: any[] = []
        let firstResponseReceived = false
        
        // 监听所有网络响应
        page.on('response', async (response: any) => {
          const url = response.url()
          if (url.includes('/api/buyin/marketing/anchor_coupon/promotion_list')) {
            try {
              const data = await response.json()
              if (data?.data?.list && data.data.list.length > 0) {
                logger.info(`拦截到商品数据，共 ${data.data.list.length} 条`)
                allPromotions.push(...data.data.list)
                firstResponseReceived = true
              }
            } catch (err) {
              logger.warn('解析响应数据失败:', errorMessage(err))
            }
          }
        })

        // 点击"直播商品"标签，触发数据加载
        logger.info('点击"直播商品"标签...')
        try {
          const liveProductTab = await page.waitForSelector(
            'label:has-text("直播商品"), div:has-text("直播商品")',
            { timeout: 10000 }
          )
          await liveProductTab.click()
          logger.info('成功点击直播商品标签')
        } catch (err) {
          logger.error('点击直播商品标签失败，尝试备用方案')
          await page.evaluate(() => {
            const labels = Array.from(document.querySelectorAll('label, div'))
            const label = labels.find(l => l.textContent?.includes('直播商品'))
            if (label) {
              (label as HTMLElement).click()
            }
          })
        }

        // 等待第一个响应
        logger.info('等待数据加载...')
        let waitCount = 0
        while (!firstResponseReceived && waitCount < 30) {
          await page.waitForTimeout(500)
          waitCount++
        }

        if (!firstResponseReceived) {
          throw new Error('等待数据超时，未收到接口响应')
        }

        logger.info('第一批数据已接收，检查是否需要加载更多...')
        await page.waitForTimeout(1000)

        // 如果第一页数据少于200条，且看起来还有更多数据，主动请求剩余数据
        if (allPromotions.length > 0 && allPromotions.length < 200) {
          logger.info('尝试获取剩余分页数据...')
          let currentPage = 2
          const pageSize = 200

          while (allPromotions.length < 200) {
            try {
              const promotionList = await page.evaluate(async (pageNum: number, size: number) => {
                const response = await fetch(
                  `/api/buyin/marketing/anchor_coupon/promotion_list?page=${pageNum}&size=${size}&search_type=1&need_channel=true`,
                  {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                      'Accept': '*/*',
                      'Accept-Language': 'zh-CN,zh;q=0.9',
                    },
                  },
                )

                if (!response.ok) {
                  return null
                }

                return await response.json()
              }, currentPage, pageSize)

              if (promotionList?.data?.list && promotionList.data.list.length > 0) {
                allPromotions.push(...promotionList.data.list)
                logger.info(`已获取第 ${currentPage} 页，共 ${promotionList.data.list.length} 条数据`)
                
                // 检查是否还有更多数据
                const total = promotionList.data.total || 0
                if (allPromotions.length >= total) {
                  break
                }
                
                currentPage++
              } else {
                break
              }
            } catch (err) {
              logger.warn(`获取第 ${currentPage} 页数据失败:`, errorMessage(err))
              break
            }
          }
        }

        logger.success(`成功获取佣金率数据，共 ${allPromotions.length} 条`)

        // 关闭弹窗（返回控制台页面）
        await page.keyboard.press('Escape')
        await page.waitForTimeout(500)
        await page.keyboard.press('Escape')
        await page.waitForTimeout(500)

        return {
          success: true,
          data: allPromotions,
        }
      } catch (error) {
        logger.error('获取佣金率数据失败:', errorMessage(error))
        return {
          success: false,
          error: errorMessage(error),
        }
      }
    },
  )
}

export function setupDarenJuanIpcHandlers() {
  setupIpcHandlers()
}

